<template>
  <div id="hy-swiper">
    <div
      class="swiper"
      @touchstart="touchstart"
      @touchmove="touchmove"
      @touchend="touchend"
    >
      <slot></slot>
    </div>
    <div class="indicator">
      <slot name="indicator" v-if="showIndicator && slideCount > 1">
        <div
          v-for="(item, index) in slideCount"
          class="indi-item"
          :class="{ active: index === currentIndex - 1 }"
          :key="index"
        ></div>
      </slot>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Swiper',
  props: {
    interval: {
      type: Number,
      default: 3000
    },
    animDuration: {
      type: Number,
      default: 300
    },
    moveRatio: {
      type: Number,
      default: 0.25
    },
    showIndicator: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      slideCount: 0, // 元素个数
      totalWidth: 0, // 图片的宽度
      currentIndex: 1, // 当前的位置
      scrolling: false, // 是否在滚动
      swiperStyle: {} // 轮播图的样式
    }
  },
  mounted() {
    setTimeout(() => {
      this.handleDom()
      this.startTime()
    }, 1000)
  },
  methods: {
    // 操作DOM
    handleDom() {
      const swiper = document.querySelector('.swiper')
      const slide = swiper.querySelectorAll('.slide')
      this.slideCount = slide.length

      if (this.slideCount > 1) {
        const cloneFirst = slide[0].cloneNode(true)
        const cloneLast = slide[slide.length - 1].cloneNode(true)
        swiper.insertBefore(cloneLast, slide[0])
        swiper.appendChild(cloneFirst)

        this.totalWidth = swiper.offsetWidth
        this.swiperStyle = swiper.style
      }
      this.rollPosition(-this.totalWidth)
    },
    // 调整位置
    rollPosition(position) {
      this.swiperStyle.transform = `translate3d(${position}px, 0, 0)`
      this.swiperStyle['-webkit-transform'] = `translate3d(${position}px), 0, 0`
      this.swiperStyle['-ms-transform'] = `translate3d(${position}px), 0, 0`
    },
    // 定时器
    startTime: function () {
      this.timr = window.setInterval(() => {
        this.currentIndex++
        this.scrollContent()
      }, this.interval)
    },
    // 滑动到正确的位置
    scrollContent() {
      this.scrolling = true
      // TMD单位多了个空格
      this.swiperStyle.transition = 'transform ' + this.animDuration + 'ms'
      this.rollPosition(-this.currentIndex * this.totalWidth)
      this.checkPosition()
      this.scrolling = false
    },
    // 清除定时器
    removeTime() {
      window.clearInterval(this.timr)
    },
    // 位置
    checkPosition() {
      window.setTimeout(() => {
        this.swiperStyle.transition = '0ms'
        if (this.currentIndex >= this.slideCount + 1) {
          this.currentIndex = 1
          this.rollPosition(-this.currentIndex * this.totalWidth)
        } else if (this.currentIndex <= 0) {
          this.currentIndex = this.slideCount
          this.rollPosition(-this.currentIndex * this.totalWidth)
        }

        // 2.结束移动后的回调
        this.$emit('transitionEnd', this.currentIndex - 1)
      }, this.animDuration)
    },
    // 触摸开始
    touchstart(e) {
      if (this.scrolling) return
      this.removeTime()
      this.startX = e.touches[0].pageX
    },
    // 滑动
    touchmove(e) {
      // 获取滑动时的坐标
      this.currentX = e.touches[0].pageX
      // 拿滑动时的坐标减去第一次触摸时的坐标
      this.distance = this.currentX - this.startX
      // 获取swiper的宽度
      const currentPosition = -this.currentIndex * this.totalWidth
      // 把swiper的宽度和滑动的距离相加
      const movePosition = currentPosition + this.distance

      this.rollPosition(movePosition)
    },
    // 触摸结束
    touchend(e) {
      const currentMove = Math.abs(this.distance)
      const swiperWidth = this.totalWidth * this.moveRatio

      // 判断是否有滑动
      if (this.distance === 0) {
        return
      } else if (this.distance > 0 && currentMove > swiperWidth) {
        this.currentIndex--
      } else if (this.distance < 0 && currentMove > swiperWidth) {
        this.currentIndex++
      }

      this.scrollContent()
      this.startTime()
    }
  }
}
</script>

<style lang="less" scoped>
#hy-swiper {
  overflow: hidden;
  position: relative;
}

.swiper {
  display: flex;
}

.indicator {
  display: flex;
  justify-content: center;
  position: absolute;
  width: 100%;
  bottom: 8px;
}

.indi-item {
  box-sizing: border-box;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #fff;
  margin: 0 5px;
}

.indi-item.active {
  background-color: rgba(212, 62, 46, 1);
}
</style>
